package com.cai.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.cai.dao.RoleDao;
import com.cai.entity.PageResult;
import com.cai.entity.QueryPageBean;
import com.cai.pojo.Permission;
import com.cai.pojo.Role;
import com.cai.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //使用分页助手
        PageHelper.startPage(currentPage, pageSize);
        Page<Role> page =roleDao.selectByCondition(queryString);
        long total = page.getTotal();
        List<Role> rows = page.getResult();
        return new PageResult(total, rows);

    }
    public List<Permission> findAll() {
        return roleDao.findAll();
    }
    //新增角色,关联检查项
    public void add(Role role, Integer[] permissionIds) {
        //1.t_role表 2.t_role_permission表
        roleDao.add(role);
        //操作关联表t_role_permission
        Integer roleId = role.getId();
        setRoleAndPermission(roleId, permissionIds);
    }
    public void delete(Integer id) {
        //先判断是否关联中间表
        List<Integer> list = roleDao.findPermissionIdsByRoleId(id);
        if(list.size()>0&&list!=null){
            roleDao.deleteAssociation(id);
        }
        roleDao.delete(id);
    }
    //编辑检查项,同时需要更新和检查项的关联关系
    public void edit(Role role, Integer[] permissionIds) {
        //1.先根据角色id清除中间表的关联关系
        roleDao.deleteAssociation(role.getId());
        //2.重新建立中间关联关系
        Integer permissionId = role.getId();
        setRoleAndPermission(permissionId,permissionIds);
        //3.更新角色表
        roleDao.edit(role);
    }
    //根据角色id查询权限
    public List<Integer> findPermissionIdsByRoleId(Integer id) {
        return roleDao.findPermissionIdsByRoleId(id);
    }
    public Role findById(Integer id) {

        return roleDao.findRoleById(id);
    }
    //定义方法用于建立中间表关联
    public void setRoleAndPermission(Integer roleId, Integer[] permissionIds) {
        if (permissionIds != null && permissionIds.length > 0) {
            for (Integer permissionId : permissionIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("role_id",roleId);
                map.put("permission_id", permissionId);
                roleDao.setRoleAndPermission(map);
            }
        }
    }
}
